# Create your views here.
from pprint import pprint
from django.contrib.auth.decorators import login_required
from django.core import serializers
from django.forms.models import inlineformset_factory, modelformset_factory, ModelForm

from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from datetime import datetime
from django.template.context import RequestContext
from django import forms
from django.utils import simplejson
from verkefni3.models import Exam, ExamQuestion, ExamAnswer, StudentExam, StudentExamAnswers
from django.forms.models import ModelForm
from django.contrib.auth import authenticate, login, logout
from django.db import IntegrityError



def home(request):
    return render_to_response("home.html", context_instance = RequestContext(request))

def exams_home(request):
    return render_to_response("hometeacher.html", context_instance = RequestContext(request))

def studend_home(request):
    return render_to_response("homestudent.html", context_instance = RequestContext(request))

def edit_question_save(request):
    if request.is_ajax():
        if request.method == 'GET':
            #TODO update Question
            message = "This is an XHR GET request"
        elif request.method == 'POST':
            question = request.POST.get('qu')
            points = request.POST.get('pt')
            questionToEditId = request.POST.get('id')
            questionToEdit = ExamQuestion.objects.get(id = questionToEditId)
            questionToEdit.question = question
            questionToEdit.point = points
            questionToEdit.save()
            data = serializers.serialize('json', [questionToEdit])
            #message = question
            # Here we can access the POST data
    else:
        message = "No XHR"
    return HttpResponse(data,'application/javascript')

def edit_question(request):
    if request.is_ajax():
        if request.method == 'GET':
            message = "This is an XHR GET request"
        elif request.method == 'POST':
            questionToEditId = request.POST.get('id')
            questionToEdit = ExamQuestion.objects.get(id = questionToEditId)
            data = serializers.serialize('json', [questionToEdit])
            #message = question
    else:
        message = "No XHR"
    return HttpResponse(data,'application/javascript')

def delete_question(request):
    if request.is_ajax():
        if request.method == 'GET':
            message = "This is an XHR GET request"
        elif request.method == 'POST':
            questionToDeleteId = request.POST.get('id')
            answersToDelete = ExamAnswer.objects.filter(question = questionToDeleteId)
            for item in answersToDelete:
                item.delete()
            questionToDelete = ExamQuestion.objects.get(id = questionToDeleteId)
            deleteditem = questionToDelete
            data = serializers.serialize('json', [deleteditem])
            questionToDelete.delete()
            #message = question
    else:
        message = "No XHR"
    return HttpResponse(data,'application/javascript')

def add_question(request):
    if request.is_ajax():
        if request.method == 'GET':
            #TODO update Question
            message = "This is an XHR GET request"
        elif request.method == 'POST':
            question = request.POST.get('qu')
            points = request.POST.get('pt')
            exid = request.POST.get('id')
            foreign_exam = Exam.objects.get(id = exid)
            new_question = ExamQuestion(question = question, exam = foreign_exam, point = points)
            new_question.save()
            data = serializers.serialize('json', [new_question])
            #message = question
            # Here we can access the POST data
    else:
        message = "No XHR"
    return HttpResponse(data,'application/javascript')

def add_answer(request):
    if request.is_ajax():
        if request.method == 'GET':
            #TODO update Question
            message = "This is an XHR GET request"
        elif request.method == 'POST':
            answers = request.POST.get('ans')
            corrects = True
            if request.POST.get('corr') == "0":
                corrects = False
            exid = request.POST.get('id')
            foreign_question = ExamQuestion.objects.get(id = exid)
            new_ans = ExamAnswer(answer = answers, correct = corrects, question = foreign_question)
            new_ans.save()
            data = serializers.serialize('json', [new_ans])
            #message = question
            # Here we can access the POST data
    else:
        message = "No XHR"
    return HttpResponse(data,'application/javascript')

def edit_answer(request):
    if request.is_ajax():
        if request.method == 'GET':
            message = "This is an XHR GET request"
        elif request.method == 'POST':
            answerToEditId = request.POST.get('id')
            answerToEdit = ExamAnswer.objects.get(id = answerToEditId)
            data = serializers.serialize('json', [answerToEdit])
            #message = question
    else:
        message = "No XHR"
    return HttpResponse(data,'application/javascript')

def edit_answer_save(request):
    if request.is_ajax():
        if request.method == 'GET':
            #TODO update Question
            message = "This is an XHR GET request"
        elif request.method == 'POST':
            answers = request.POST.get('ans')
            corrects = True
            if request.POST.get('corr') == "0":
                corrects = False
            answerToEditId = request.POST.get('id')
            answerToEdit = ExamAnswer.objects.get(id = answerToEditId)
            answerToEdit.answer = answers
            answerToEdit.correct = corrects
            answerToEdit.save()
            data = serializers.serialize('json', [answerToEdit])
            #message = question
            # Here we can access the POST data
    else:
        message = "No XHR"
    return HttpResponse(data,'application/javascript')

def delete_answer(request):
    if request.is_ajax():
        if request.method == 'GET':
            message = "This is an XHR GET request"
        elif request.method == 'POST':
            answerToDeleteId = request.POST.get('id')
            answerToDelete = ExamAnswer.objects.get(id = answerToDeleteId)
            data = serializers.serialize('json', [answerToDelete])
            answerToDelete.delete()
            #message = question
    else:
        message = "No XHR"
    return HttpResponse(data,'application/javascript')

#@login_required(redirect_field_name='my_redirect_field')
def student_current_exams(request):
    coll_exams = Exam.objects.filter(deadline__gte = datetime.now())
    studentFinishedAreOngoing = StudentExam.objects.filter(student = "Gudrun")
    for ongoing in studentFinishedAreOngoing:
        coll_news = coll_exams.exclude(id = ongoing.exam_id)
        coll_exams = coll_news

    return render_to_response("availableexams.html", { 'collection' : coll_exams }, context_instance = RequestContext(request))

def student_finished_exams(request):
    coll_exams = StudentExam.objects.filter( student = "Gudrun", finished = True)
    return render_to_response("closedexams.html", { 'collection' : coll_exams }, context_instance = RequestContext(request))

def student_ongoing_exams(request):
    coll_exams = StudentExam.objects.filter( student = "Gudrun", finished = False)

    return render_to_response("ongoingexams.html", { 'collection' : coll_exams }, context_instance = RequestContext(request))

def student_taking_exam(request, exam_id):

    exam = Exam.objects.get(id=exam_id)
    questions = ExamQuestion.objects.filter(exam = exam_id)
    for item in questions:
        item.answers = ExamAnswer.objects.filter(question = item.id)
    if request.method == 'POST':
        tmp_post = request.POST.copy()
        action = tmp_post['submit']
        del tmp_post['csrfmiddlewaretoken']
        del tmp_post['submit']
        foreignExam = Exam.objects.get(id=exam_id)

        if(action== "Submit"):
            #TODO its finished now we can calculate the grade an put it in
            try:
                tryStudentExam, create = StudentExam.objects.get_or_create(student="Gudrun" , exam=foreignExam , finished=True , grade=0)

                if(create == False):
                    tryStudentExam.finished = True
                    tryStudentExam.save()

            except IntegrityError:
                tryStudentExam = StudentExam.objects.get(exam = foreignExam.id)
                tryStudentExam.finished = True
                tryStudentExam.save()
        else:
            try:
                tryStudentExam, created = StudentExam.objects.get_or_create(student="Gudrun" , exam=foreignExam , finished=False , grade=0)
            except IntegrityError:
                tryStudentExam = StudentExam.objects.get(exam = foreignExam.id)

        for item in tmp_post:
            answersId = request.POST.get(item)
            foreignAnswer = ExamAnswer.objects.get(id = answersId)
            foreignQuestion = ExamQuestion.objects.get(id = foreignAnswer.question.id)

            try:
                tryAnswer, create = StudentExamAnswers.objects.get_or_create(studentAnswer = foreignAnswer, studentExam = tryStudentExam, studentQuestion = foreignQuestion)
                if(create == False):
                    tryAnswer.studentAnswer = foreignAnswer
                    tryAnswer.save()
            except IntegrityError:
                answersFromStudent = StudentExamAnswers.objects.get(studentExam = tryStudentExam.id, studentQuestion = foreignQuestion.id)
                answersFromStudent.studentAnswer = foreignAnswer
                answersFromStudent.save()

        if(action == "Submit"):
            getAnswers = StudentExamAnswers.objects.filter( studentExam = exam_id)
            getQuestions = ExamQuestion.objects.filter(exam = exam_id)
            fullTest = 0
            for question in getQuestions:
                    fullTest = fullTest + question.point
            grade = 0
            for answer in getAnswers:
                if (answer.studentAnswer.correct == True):
                    grade = grade + answer.studentQuestion.point
            realGrade = (round((float(grade)/fullTest)*10))
            fixGradeStudentExam = StudentExam.objects.get(exam = foreignExam.id)
            fixGradeStudentExam.grade = realGrade
            fixGradeStudentExam.save()
            return HttpResponseRedirect('/AvailableExams/') # Redirect after POST
        else:
            answers = StudentExamAnswers.objects.filter(studentExam = tryStudentExam.id).values_list('studentAnswer', flat= True)
            numberOfQuestion = ExamQuestion.objects.filter(exam = exam_id).count()
            numberOfAnswers = answers.count()
            progress = (float(numberOfAnswers)/numberOfQuestion) * 100
            return render_to_response('studentexamination.html', {
                'exam':exam,
                'questions':questions,
                'answers': answers,
                'progress' : progress,
                },context_instance = RequestContext(request))
    else:
        try:
            foreignExam = Exam.objects.get(id=exam_id)
            tryStudentExam = StudentExam.objects.get(exam = foreignExam.id)
            answers = StudentExamAnswers.objects.filter(studentExam = tryStudentExam.id).values_list('studentAnswer', flat= True)
            numberOfQuestion = ExamQuestion.objects.filter(exam = exam_id).count()
            progress = (float(answers.count())/numberOfQuestion) * 100
            pprint(progress)
        except:
            answers = None
            progress = 0
        return render_to_response('studentexamination.html', {
        'exam':exam,
        'questions':questions,
        'answers': answers,
        'progress' : progress,
        },context_instance = RequestContext(request))

def all_exams(request):
    coll_exams = Exam.objects.filter(author = "Patrekur")
    return render_to_response("allexams.html",{ 'collection' : coll_exams }, context_instance = RequestContext(request))

def finished_exams(request):
    coll_exams = Exam.objects.filter(author = "Patrekur").filter(deadline__lt=datetime.now())
    return render_to_response("finishedexams.html", { 'collection' : coll_exams }, context_instance = RequestContext(request))

def current_exams(request):
    coll_exams = Exam.objects.filter(author = "Patrekur").filter(deadline__gte=datetime.now())
    return render_to_response("currentexams.html", { 'collection' : coll_exams }, context_instance = RequestContext(request))

def create_exam(request):
    if request.method == 'POST':
        form = ExamForm(request.POST)
        if form.is_valid():
            new_exam = Exam(name = form.cleaned_data["name"], description = form.cleaned_data["description"], deadline = form.cleaned_data["deadline"], author = "Patrekur")
            new_exam.save()
            return HttpResponseRedirect('/AllExams/') # Redirect after POST
    else:
        form = ExamForm()
    return render_to_response('examform.html', {
        'form': form,
        },context_instance = RequestContext(request))

def delete_exams(request, exam_id):
    exam = Exam.objects.get(id = exam_id)
    if request.method == "POST":
        exam.delete()
        return HttpResponseRedirect('/AllExams/') # Redirect after POST
    else:
        if exam:
            return render_to_response("examformdelete.html",{ 'obj' : exam }, context_instance = RequestContext(request))
        else:
            return render_to_response("notfound.html", context_instance = RequestContext(request))

class ExamForm(forms.Form):
    name = forms.CharField(max_length=64, required=True)
    description = forms.CharField(max_length=64, required=True)
    deadline = forms.DateTimeField()

class ExamFormEdit(ModelForm):
    class Meta:
        model = Exam
        exclude = ("finished", "author" )

def edit_exams(request,exam_id):
    exam = Exam.objects.get(id = exam_id)
    if request.method == 'POST':
        form = ExamFormEdit(request.POST, instance = exam)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/AllExams/') # Redirect after POST
    else:
        if exam:
            form = ExamFormEdit(instance=exam)
        else:
            return render_to_response("notfound.html", context_instance = RequestContext(request))
    return render_to_response('examsformedit.html', {
        'form': form,
        'exam_id':exam_id,
        },context_instance = RequestContext(request))


def detail_exams(request, exam_id):
    exam = Exam.objects.get(id = exam_id)
    if exam:
        questions = ExamQuestion.objects.all().filter(exam = exam.id)
        for item in questions:
            item.answers = ExamAnswer.objects.filter(question = item.id)

        return render_to_response("examdetail.html",{ 'obj' : exam, 'questions' : questions }, context_instance = RequestContext(request))
    else:
        return render_to_response("notfound.html", context_instance = RequestContext(request))
def create_question(request, exam_id):
    if request.method == 'POST':
        form = QuestionForm(request.POST)
        if form.is_valid():
            new_question = ExamQuestion(question = form.cleaned_data["question"],   )
            new_exam.save()
            return HttpResponseRedirect('/AllExams/') # Redirect after POST
    else:
        form = ExamForm()
    return render_to_response('examform.html', {
        'form': form,
        },context_instance = RequestContext(request))

def detail_question(request, exam_id):
    question = ExamQuestion.objects.get(id = exam_id)
    if question:
        answers = ExamAnswer.objects.filter(question = question.id)
        return render_to_response("questiondetail.html",{ 'question' : question, 'answers' : answers }, context_instance = RequestContext(request))
    else:
        return render_to_response("notfound.html", context_instance = RequestContext(request))



